package com.mtiiot.fstask.task;

import com.mtiiot.fscore.bean.MetadataInfo;
import com.mtiiot.fscore.inter1.LogService1;
import com.mtiiot.fscore.utils.LogLevel;
import com.mtiiot.fstask.esdao.BaseElasticsearch;
import com.mtiiot.fstask.utils.Contants;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.valuecount.ValueCount;
import smscenter.WsSendSmsStub;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Created by Administrator on 16-6-22.
 */

//@Component("logAlertedTask")
public class LogAlertedTask {
    private static final Logger logger = LogManager.getLogger(LogAlertedTask.class);
    private String phone;
//    private Map<String,String> logMap;
    private String queryMinute;
    private String queryTimeFormat;
    private String logTimeFormat;
    private BaseElasticsearch baseElasticsearch;
    //private static ESClient esClient=new ESClient();
    //private LogService logService;
    private LogService1 logService1;


    public synchronized void execute1(){
        logger.info("========日志短信预警定时任务开始执行==========");
        Client client=null;
        try{
            client=baseElasticsearch.getEsDataSource().getClient();
            BoolQueryBuilder bq=QueryBuilders.boolQuery();
            BoolQueryBuilder should= QueryBuilders.boolQuery();
            should.should(QueryBuilders.termQuery("logLevel", "error"));
            should.should(QueryBuilders.termQuery("logLevel", "logic"));
            bq.must(should);
            Date now=new Date();
            Calendar cal=Calendar.getInstance();
            cal.setTime(now);
            int m=Integer.parseInt(queryMinute);
            cal.add(Calendar.MINUTE,-m);
            bq.must(QueryBuilders.rangeQuery("time").from(cal.getTimeInMillis()).to(now.getTime()));
            QueryBuilder queryBuilder = bq;

            SearchRequestBuilder srb = client.prepareSearch(Contants.INDEX_METADATA)
                    .setTypes(Contants.TYPE_METADATA_LOG)
                    .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                    .setExplain(true)
                    .setSize(10);
            // 最后就是返回搜索响应信息
            srb.setQuery(bq);
            srb.addAggregation(AggregationBuilders.terms("sysStat").field("sysName")
                    .subAggregation(AggregationBuilders.terms("logLevelStat").field("logLevel")
                            .subAggregation(AggregationBuilders.count("countStat").field("logLevel"))));
            SearchResponse response =srb.execute().actionGet();
            SearchHits sh=response.getHits();
            long totalHits=sh.totalHits();
            if(totalHits==0){
                logger.info("========最近"+queryMinute+"分钟无异常==========");
                return;
            }
            Aggregations sysAggr=response.getAggregations();
            Terms terms=sysAggr.get("sysStat");
            List<Terms.Bucket> list=terms.getBuckets();
            StringBuffer sb=new StringBuffer("【仪器平台】最近"+queryMinute+"分钟异常信息:\r\n");
            for(Terms.Bucket b:list){
                String sysName=b.getKey().toString();
                sb.append(sysName+":{");
                Aggregations logLevelAggr=b.getAggregations();

                Terms terms1=logLevelAggr.get("logLevelStat");
                List<Terms.Bucket> list1=terms1.getBuckets();
                int i=0;
                for(Terms.Bucket b1:list1){
                    String logLevel=b1.getKey().toString();
                    if(i!=0){
                        sb.append(",");
                    }
                    sb.append(logLevel+":");
                    Aggregations countAggr=b1.getAggregations();
                    ValueCount vc=countAggr.get("countStat");
                    long count=vc.getValue();
                    sb.append(count);
                    i++;
                }
                sb.append("}\r\n");
            }
            //System.out.println(sb.toString());

            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
            //content+="\r\n请查看日志系统并及时处理"+dateFormat1.format(new Date());
            sb.append("请及时处理!"+dateFormat1.format(new Date()));
            WsSendSmsStub ws=new WsSendSmsStub();
            WsSendSmsStub.OutSendSms oss=new WsSendSmsStub.OutSendSms();
            oss.setStrPhone(phone);
            oss.setStrContent(sb.toString());
            oss.setSendDate(dateFormat1.format(new Date()));
            oss.setCallerid("call001");
            oss.setAccesskey("123456");
            oss.setSendid("xxxx");
            oss.setSourcecode("xxxx");
            ws.outSendSms(oss);
        }catch (Exception e){
            logService1.sendLog(new MetadataInfo(Contants.SYS_ID_FS, Contants.FSTASK_HOST, Contants.MODULE_FSTASK, "LogAlertedTask", "execute1"),LogLevel.ERROR,"",e.getMessage());
            logger.error(e.getMessage(), e);
        }finally {
            if(client!=null){
                try {
                    baseElasticsearch.getEsDataSource().releaseClient(client);
                } catch (Exception e) {
                    logService1.sendLog(new MetadataInfo(Contants.SYS_ID_FS, Contants.FSTASK_HOST, Contants.MODULE_FSTASK, "LogAlertedTask", "execute1"), LogLevel.ERROR, "releaseClient Exception!!", e.getMessage());
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }

    public synchronized void execute(){
//        logger.info("========日志短信预警定时任务开始执行==========");
//        try {
//            if(esClient==null){
//                esClient=new ESClient();
//            }
//            Client client =esClient.client;
//
//            Set<String> keys =logMap.keySet();
//            Date now=new Date();
//            int m=Integer.parseInt(queryMinute);
//            Date now_10 = new Date(now.getTime() - m*60*1000); //N分钟前的时间 N*60*1000
//            SimpleDateFormat dateFormat = new SimpleDateFormat(queryTimeFormat);//可以方便地修改日期格式
//            String startTime=dateFormat.format(now_10);
//            String endTime=dateFormat.format(now);
//            String content="【仪器平台】最近"+queryMinute+"分钟异常信息:";
//            boolean hasLog=false;
//            for(String key:keys){
//                SearchResponse response = client.prepareSearch(key)//可以同时搜索多个索引prepareSearch("index","index2")
//                        .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
//                        .setPostFilter(QueryBuilders.rangeQuery("@timestamp").from(startTime).to(endTime))
//                        .execute()
//                        .actionGet();
//
//                long num=response.getHits().getTotalHits();
//                if(num>0){
//                    hasLog=true;
//                    content+="\r\n"+logMap.get(key)+num;
//                }
//            }
//            if(!hasLog){
//                logger.info("========最近"+queryMinute+"分钟无异常==========");
//                return;
//            }
//
//            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
//            content+="\r\n请查看日志系统并及时处理"+dateFormat1.format(new Date());
//            logger.info(content);
//            WsSendSmsStub ws=new WsSendSmsStub();
//            WsSendSmsStub.OutSendSms oss=new WsSendSmsStub.OutSendSms();
//            oss.setStrPhone(phone);
//            oss.setStrContent(content);
//            oss.setSendDate(dateFormat1.format(new Date()));
//            oss.setCallerid("call001");
//            oss.setAccesskey("123456");
//            oss.setSendid("xxxx");
//            oss.setSourcecode("xxxx");
//            ws.outSendSms(oss);
//        } catch (Exception e) {
//            logService.sendLog(SysName.SYSNAME_FS, LogLevel.ERROR, Contants.MODULE_FSTASK,"LogAlertedTask","execute","",e.getMessage(),Contants.FSTASK_HOST);
//            logger.error(e.getMessage(), e);
//        }
    }



    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

//    public Map<String, String> getLogMap() {
//        return logMap;
//    }
//
//    public void setLogMap(Map<String, String> logMap) {
//        this.logMap = logMap;
//    }

    public String getQueryMinute() {
        return queryMinute;
    }

    public void setQueryMinute(String queryMinute) {
        this.queryMinute = queryMinute;
    }

    public String getQueryTimeFormat() {
        return queryTimeFormat;
    }

    public void setQueryTimeFormat(String queryTimeFormat) {
        this.queryTimeFormat = queryTimeFormat;
    }

    public String getLogTimeFormat() {
        return logTimeFormat;
    }

    public void setLogTimeFormat(String logTimeFormat) {
        this.logTimeFormat = logTimeFormat;
    }
//    public LogService getLogService() {
//        return logService;
//    }
//
//    public void setLogService(LogService logService) {
//        this.logService = logService;
//    }
    public BaseElasticsearch getBaseElasticsearch() {
        return baseElasticsearch;
    }

    public void setBaseElasticsearch(BaseElasticsearch baseElasticsearch) {
        this.baseElasticsearch = baseElasticsearch;
    }

    public LogService1 getLogService1() {
        return logService1;
    }

    public void setLogService1(LogService1 logService1) {
        this.logService1 = logService1;
    }
}
